<template>
  <div class="page-miH page-bgBack">
    <PageHeader subTitle="返回" @back="goBack">
      <span>供应商</span>
    </PageHeader>
    <a-spin :spinning="spinning" class="pb48 formStyle" style="width: 840px; margin: 0 auto">
      <Collapse title="基本信息" :disabled="basicFormJson.editable" :showBtns="mode !== 'add'" @edit="onEdits('basicFormJson')">
        <DynamicForm
          v-if="basicData"
          ref="basic"
          :dataSource="basicData"
          :editable.sync="basicFormJson.editable"
          :dynamicData="{}"
          :formFields="basicFormJson.fields"
          :sortedKeys="basicFormJson.sortedKeys"
          :formConfig="{}"
          :showBtns="mode !== 'add'"
          formLayout="vertical"
          class="pt16"
          style="max-width: 880px; margin: 0 auto"
          @change="dynamicChange($event, 'basicFormJson')"
        />
      </Collapse>
      <Collapse title="联系信息" :disabled="contactFormJson.editable" :showBtns="mode !== 'add'" @edit="onEdits('contactFormJson')">
        <DynamicForm
          v-if="contactData"
          ref="contact"
          :dataSource="contactData"
          :editable.sync="contactFormJson.editable"
          :dynamicData="{}"
          :formFields="contactFormJson['fields']"
          :sortedKeys="contactFormJson.sortedKeys"
          :formConfig="{}"
          :showBtns="mode !== 'add'"
          formLayout="vertical"
          class="pt16"
          style="max-width: 880px; margin: 0 auto"
          @change="dynamicChange($event, 'contactFormJson')"
        />
      </Collapse>
      <Collapse title="法人信息" :disabled="corporateFormJson.editable" :showBtns="mode !== 'add'" @edit="onEdits('corporateFormJson')">
        <DynamicForm
          v-if="corporateData"
          ref="corporate"
          :dataSource="corporateData"
          :editable.sync="corporateFormJson.editable"
          :dynamicData="{}"
          :formFields="corporateFormJson.fields"
          :sortedKeys="corporateFormJson.sortedKeys"
          :formConfig="{}"
          :showBtns="mode !== 'add'"
          formLayout="vertical"
          class="pt16"
          style="max-width: 880px; margin: 0 auto"
          @change="dynamicChange($event, 'corporateFormJson')"
        />
      </Collapse>
      <div v-if="mode === 'add'" class="bgc-white fixedBtn">
        <a-space>
          <a-button @click="goBack">返回</a-button>
          <a-button type="primary" @click="saveActive">保存</a-button>
        </a-space>
      </div>
    </a-spin>
  </div>
</template>
<script>
import { findFormGysReq, gysCreateReq, gysUpdateReq, gysDetailReq } from "./api";
import { basicsPagesNew } from "@/utils/dynamic";
import { formatValues, deFormatValues } from "./funcs";
export default {
  name: "",
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      basicData: null,
      contactData: null,
      corporateData: null,
      basicFormJson: {},
      contactFormJson: {},
      corporateFormJson: {},
      spinning: false
    };
  },
  computed: {
    mode() {
      return this.$route.query.mode;
    },
    groupId() {
      return this.$route.query.groupId;
    },
    gysId() {
      return this.$route.query.gysId;
    },
    areaSourceMap() {
      return this.$store.state.common.areaSourceMap;
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.loadFields();
  },
  methods: {
    async saveActive() {
      const refs = ["basic", "contact", "corporate"];
      let list = [];
      let flag = true;
      for (let i = 0; i < refs.length; i++) {
        const ref = refs[i];
        const node = this.$refs[ref];
        if (node) {
          const res = await node.saveActive();
          if (!res.success && res.error) {
            flag = false;
          } else {
            list = [].concat(list, formatValues(res, this[`${ref}FormJson`]["fields"], this.areaSourceMap));
          }
        }
      }
      if (list.length > 0 && flag) {
        this.spinning = true;
        gysCreateReq({
          groupId: this.groupId,
          list
        })
          .then((res) => {
            this.spinning = false;
            this.$message.success("保存成功");
            this.goBack();
          })
          .catch((err) => {
            this.spinning = false;
            this.$message.error(err.message);
          });
      } else {
        this.$message.warning("请填写完整信息");
      }
    },
    dynamicChange(value, formJson) {
      if (value) {
        const list = formatValues(value, this[formJson]["fields"], this.areaSourceMap);
        if (list.length > 0) {
          gysUpdateReq({
            id: this.gysId,
            groupId: this.groupId,
            list
          })
            .then((res) => {
              this.$message.success("保存成功");
              this[formJson].editable = false;
              this.loadFieldValue();
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        }
      }
    },
    onEdits(sign) {
      this[sign].editable = true;
    },
    loadFields() {
      findFormGysReq()
        .then((res) => {
          for (let i = 0; i < res.data.length; i++) {
            const mod = res.data[i];
            const obj = {
              editable: this.mode === "add",
              fields: {},
              sortedKeys: {}
            };
            const { fields, fieldKeys } = basicsPagesNew(null, mod.moduleCode, mod.formGroupFieldList);
            obj.fields = fields;
            obj.sortedKeys = fieldKeys;
            this[`${mod.moduleCode}FormJson`] = obj;
            if (this.mode === "add") {
              this[`${mod.moduleCode}Data`] = {};
            }
          }
          if (this.mode === "edit") {
            this.loadFieldValue();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    loadFieldValue() {
      gysDetailReq(this.gysId)
        .then((res) => {
          for (let i = 0; i < res.data.length; i++) {
            const mod = res.data[i];
            this[`${mod.moduleCode}Data`] = deFormatValues(mod.formGroupFieldList, this[`${mod.moduleCode}FormJson`]["fields"]);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    goBack() {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.fixedBtn {
  position: fixed;
  left: 204px;
  bottom: 24px;
  right: 24px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #e8e8e8;
}
::v-deep {
  .ant-calendar-picker {
    width: 100%;
  }
}
.formStyle {
  .editable-no {
    ::v-deep .ant-upload {
      display: none;
    }
    ::v-deep .anticon-delete {
      display: none !important;
    }
  }
}
</style>
